package com.handu.luna.boss.controller;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.handu.luna.core.domain.user.UserRank;

@Controller
@RequestMapping("/userRank/*")
public class UserRankController extends BaseController {
	
	@RequestMapping(value="list")
	public BossModel list(){
		return this.createModel("userRank/list").add("userRanks", context.getUserRankRepository().findAll());
	}
	
	@RequestMapping(value="edit/{id}")
	public BossModel edit(@PathVariable long id){
		return createModel("userRank/info").add("userRank",context.getUserRankRepository().findOne(id));
	}
	
	@RequestMapping(value="save",method = RequestMethod.POST)
	public BossModel save(@Valid final UserRank userRank, final BindingResult bindingResult, final ModelMap model, RedirectAttributes redirectAttributes){
		String message = userRank.getSucessFlashMessage();
		userRank.validate("userRank", bindingResult);
		if (bindingResult.hasErrors()) {			
			return createModel("userRank/info").add("userRank",userRank);
		}	
		context.getUserRankRepository().save(userRank);
		redirectAttributes.addFlashAttribute("message", message);
		return createModel("redirect:list");
	}
	
	@RequestMapping(value="add")
	public BossModel add(){
		return createModel("userRank/info").add("userRank",new UserRank());
	}
	
	@RequestMapping(value="delete",method= RequestMethod.POST)
	public BossModel delete( long id){
		context.getUserRankRepository().findOne(id).validateBeforeDelete();
		context.getUserRankRepository().delete(id);
		return createModel("userRank/userRank_table").add("userRanks",context.getUserRankRepository().findAll());
	}
}
